package cn.itcast.service.impl;

import cn.itcast.dao.AccountDao2;
import cn.itcast.domain.Account;
import cn.itcast.service.AccountService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountService2Impl implements AccountService2 {
    @Autowired
    private AccountDao2 accountDao2;
    @Autowired
    private RedisTemplate<String,List> redisTemplate;
    @Transactional(propagation = Propagation.REQUIRED)
    public void transfer(Integer inId, Integer outId, Double money) throws Exception {
        accountDao2.inMoney(inId,money);
       /* System.out.println(1/0);*/
        accountDao2.outMoney(outId,money);
        redisTemplate.delete("findAll");
    }
    @Transactional
    public List<Account> findAll() throws Exception {
        if(redisTemplate.hasKey("findAll")){
            List findAll = redisTemplate.opsForValue().get("findAll");
            return findAll;
        }else {
            List<Account> list = accountDao2.findAll();
            redisTemplate.opsForValue().set("findAll",list);
            return list;
        }

    }

    @Transactional
    public void save(Account account) throws Exception {
        accountDao2.save(account);
        redisTemplate.delete("findAll");
    }
    @Transactional
    public void delete(Integer id) throws Exception {
        accountDao2.delete(id);
        redisTemplate.delete("findAll");
    }
}

